
const loaderUtils = require('loader-utils')
// 默认参数
const defaultsProp = {
  enabled: false, // 开启/禁用

  unitToConvert: 'px',
  viewportWidth: 1920,
  unitPrecision: 5, // numbers after `.`
  minPixelValue: 0,
  viewportUnit: 'vw'
}
const template = /<template>([\s\S]+)<\/template>/gi
const ZPXRegExp = new RegExp('(\\d+)' + defaultsProp.unitToConvert)
module.exports = function (source) {
  const opts = loaderUtils.getOptions(this)
  const defaults = Object.assign({}, defaultsProp, opts)
  let _source = ''
  if (template.test(source)) {
    _source = source.match(template)[0]
  }
  const pxGlobalRegExp = new RegExp(ZPXRegExp.source, 'ig')
  if (pxGlobalRegExp.test(_source) && defaultsProp.enabled) {
    const $source = _source.replace(
      pxGlobalRegExp,
      createPxReplace(
        defaults.viewportWidth,
        defaults.unitPrecision,
        defaults.minPixelValue,
        defaults.viewportUnit
      )
    )
    return source.replace(template, $source)
  } else {
    return source
  }
}

function createPxReplace (
  viewportSize,
  unitPrecision,
  minPixelValue,
  viewportUnit
) {
  return function (m, $1) {
    // ignoring `PX` `Px`
    if (m.indexOf('px') === -1) {
      return m
    }
    if (!$1) {
      return m
    }
    var pixels = parseFloat($1)
    if (pixels < minPixelValue) {
      return m
    }
    return toFixed((pixels / viewportSize) * 100, unitPrecision) + viewportUnit
  }
}

function toFixed (number, precision) {
  var multiplier = Math.pow(10, precision + 1)
  var wholeNumber = Math.floor(number * multiplier)
  return (Math.round(wholeNumber / 10) * 10) / multiplier
}
